<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;

class FileAccess extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('file:access')
            ->addOption('mode', 'm', Option::VALUE_OPTIONAL, '', '700')
            ->addOption('user', 'u', Option::VALUE_OPTIONAL, '', 'webu')
            ->addOption('group', 'g', Option::VALUE_OPTIONAL, '', 'webg')
            ->setDescription('文件夹权限设置');
    }

    protected function execute(Input $input, Output $output)
    {
        $mode = $input->getOption('mode');
        $user = $input->getOption('user');
        $group = $input->getOption('group');

        if (empty($mode)) {
            $output->error('The mode parameter cannot be empty.');
            return;
        }
        if (empty($user)) {
            $output->error('The user parameter cannot be empty.');
            return;
        }
        if (empty($group)) {
            $output->error('The group parameter cannot be empty.');
            return;
        }
        if (!preg_match('/^[0-7]{3}$/', $mode)) {
            $output->error("Invalid argument mode:{$mode}, Expected it to be like 700.");
            return;
        }
        $current_user = trim(shell_exec('whoami'));
        if ($current_user != 'root') {
            $output->error('You should be with administrator privileges to run this command.');
            return;
        }
        $dir = root_path();
        $result = shell_exec("chmod -R {$mode} {$dir}");
        if (!empty($result)) {
            $output->error('Change the permissions failure.');
            return;
        }
        $result = shell_exec("chown -R {$user}:{$group} {$dir}");
        if (!empty($result)) {
            $output->error('Change the owner failure.');
            return;
        }
    }
}
